const { query } = require("./access");
const child_process = require("child_process");
const { outExcel } = require("./excle");
const fs = require("fs");
const arr = [];
let result_arr = [];
const t0 = Date.now();

/**
 * @description 删除生成的数据库文件
 */
function del() {
  fs.readdir("./dataSource", (error, data) => {
    if (error) {
      console.log(error);
      return;
    }

    for (let item of data) {
      fs.unlink(`./dataSource/${item}`, (error, data) => {
        if (error) {
          console.log(error);
          return;
        }
      });
    }
  });
}
function allEnd() {
  console.log(result_arr.length);
  outExcel(result_arr);
  del();
  console.log(`总耗时${(Date.now() - t0) / 1000}秒`);
}

/**
 *
 * @returns 复制的结果
 * @author zesion Lee
 * @description 复制源数据库文件，方便不同的进程调用
 */
function copy() {
  return new Promise((resolve) => {
    fs.readdir("./数据库", async (error, data) => {
      if (data.length == 0) {
        console.log("请放入数据库文件");
        resolve(false);
      } else if (data.length > 1) {
        console.log("请将数据导入到同一个 .accdb 文件中");
        resolve(false);
      } else if (!data[0].includes("accdb")) {
        console.log("只支持 .accdb 文件");
        resolve(false);
      }

      try {
        for (let i = 1; i <= 5; i++) {
          const ws = fs.createWriteStream(`./dataSource/Database${i}.accdb`);
          fs.createReadStream("./数据库/" + data[0]).pipe(ws);
          await new Promise((resolve) => {
            ws.on("finish", (error, data) => {
              resolve();
            });
          });
        }
        resolve(true);
      } catch (error) {
        resolve(false);
      }
    });
  });
}

/**
 * @description 主函数
 */
(async function () {
  await copy();
  const airlineList = await query(`select * from flight_airline where LineType = '国内班机航线'`);

  const evey_length = Math.ceil(airlineList.length / 5);

  for (let i = 1; i <= 5; i++) {
    arr.push(i);
    const workerProcess = child_process.fork("child_process.js", [i]);

    const child_data = airlineList.slice((i - 1) * evey_length, i * evey_length);

    workerProcess.send(child_data);

    workerProcess.on("message", (msg) => {
      result_arr.push(...msg);
    });

    workerProcess.on("exit", (code) => {
      console.log("进程已退出,退出代码 " + code);
      arr.pop();
      if (arr.length == 0) {
        allEnd();
      }
    });
  }
})();
